package com.atstudy.servlet;

import com.atstudy.entites.User;
import com.atstudy.service.UserServiceImpl;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @version v1.0
 * @description:
 * @author: admin
 * @date: 2023/2/1 14:32
 * @copyright: 博为峰
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name");
        UserServiceImpl userService = new UserServiceImpl();
        User user = userService.getUserByName(name);
        if (user != null) {
            HttpSession session = req.getSession();
            session.setAttribute("user", user);
            RequestDispatcher dispatcher = req.getRequestDispatcher("/main.jsp");
            dispatcher.forward(req, resp);
        } else {
            resp.sendRedirect(req.getContextPath() + "/login.jsp");
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        //销毁session对象
        session.invalidate();
        //重定向到登录页
        resp.sendRedirect(req.getContextPath() + "/login.jsp");
    }
}
